package com.rerun.common.email;

import com.rerun.common.email.bean.Email;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * The type Mail util.
 *
 * @author dax.
 * @version v1.0
 * @since 2017 /10/9 15:47
 */
public class MailUtil {
    private static final Logger log = LoggerFactory.getLogger(MailUtil.class);
    private   String nickName;
    private   String fromEmailAddress;
    private JavaMailSender javaMailSender;
    private TaskExecutor taskExecutor;


    /**
     * Send mail.
     *
     * @param email   the email
     * @param request the request
     * @throws MessagingException the messaging exception
     * @throws IOException        the io exception
     */
    public void sendMail(Email email, HttpServletRequest request) throws MessagingException, IOException {
        /*if (email.getAddress().length > 5) {// 收件人大于5封时，采用异步发送
            sendMailByAsynchronousMode(email);
            this.message.append("收件人过多，正在采用异步方式发送...<br/>");
        } else {*/
        sendHtmlMailBySynchronizationMode(email, request);
        //this.message.append("正在同步方式发送邮件...<br/>");
        //}
    }
    public void sendSimpleMail(Email email) throws IOException, MessagingException {
        sendSimpleMailBySynchronizationMode(email);
    }

    /**
     * Send mail by asynchronous mode.
     *
     * @param email   the email
     * @param request the request
     */
    public void sendMailByAsynchronousMode(final Email email, HttpServletRequest request) {
        taskExecutor.execute(() -> {
            try {
                sendHtmlMailBySynchronizationMode(email, request);
            } catch (Exception e) {
                log.debug("mail sync send exception", e);
            }
        });
    }

    /**
     * 同步发送简单邮件.
     *
     * @param email the email
     * @throws MessagingException the messaging exception
     * @throws IOException        the io exception
     */
    private void sendSimpleMailBySynchronizationMode(Email email) throws MessagingException, IOException{
        SimpleMailMessage  message=new SimpleMailMessage();
            message.setFrom(fromEmailAddress);
            message.setSubject(email.getSubject());
            message.setTo(email.getToAddress());
            message.setText(email.getContent());
            javaMailSender.send(message);
    }
    /**
     * 同步发送html 邮件.
     *
     * @param email   the email
     * @param request the request
     * @throws MessagingException the messaging exception
     * @throws IOException        the io exception
     */
    private void sendHtmlMailBySynchronizationMode(Email email, HttpServletRequest request)
            throws MessagingException, IOException {


        MimeMessage mime = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mime, true, "utf-8");
        String nick = MimeUtility.encodeText(nickName);
        StringBuilder stringBuilder = new StringBuilder(nick);
        stringBuilder.append("<").append(fromEmailAddress).append(">");
        InternetAddress address = new InternetAddress(stringBuilder.toString());
        helper.setFrom(address);// 发件人
        helper.setTo(email.getToAddress());// 收件人
//        helper.setReplyTo(email.getFromAddress());// 回复到
        helper.setSubject(email.getSubject());// 邮件主题
        String htmlText = email.getContent();
        helper.setText(htmlText, true);// true表示设定html格式
        insertImage(request, helper, "mailbg01.png", htmlText,"mailbg01.png");
        insertImage(request, helper, "mailbg02.png", htmlText,"mailbg02.png");
        insertImage(request, helper, "qrcode.png", htmlText,"qrcode.png");
        insertImage(request, helper, "ads01.png", htmlText,"ads01.png");
          String headUrl= htmlText.contains("<span class=\"xingbie\">男")? "male.png": htmlText.contains("<span class=\"xingbie\">男")? "female.png" :null;
          if (headUrl!=null){
              insertImage(request, helper, headUrl, htmlText,headUrl);
          }
          log.info("邮件发送： {}",email.getToAddress());
        javaMailSender.send(mime);
    }

    private void insertImage(HttpServletRequest request, MimeMessageHelper helper, String imageFullName, String htmlText,String cid) throws MessagingException {
        if (htmlText.contains(imageFullName)) {
            String imageBasePath = request.getSession().getServletContext().getRealPath("/static/images");
            String path = imageBasePath +"/"+imageFullName;
            FileSystemResource img = new FileSystemResource(new File(path));
            helper.addInline(cid, img);
        }
    }

    /**
     * Gets java mail sender.
     *
     * @return the java mail sender
     */
    public JavaMailSender getJavaMailSender() {
        return javaMailSender;
    }

    /**
     * Sets java mail sender.
     *
     * @param javaMailSender the java mail sender
     */
    public void setJavaMailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    /**
     * Gets task executor.
     *
     * @return the task executor
     */
    public TaskExecutor getTaskExecutor() {
        return taskExecutor;
    }

    /**
     * Sets task executor.
     *
     * @param taskExecutor the task executor
     */
    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    /**
     * Gets nick name.
     *
     * @return the nick name
     */
    public String getNickName() {
        return nickName;
    }

    /**
     * Sets nick name.
     *
     * @param nickName the nick name
     */
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    /**
     * Gets from email address.
     *
     * @return the from email address
     */
    public String getFromEmailAddress() {
        return fromEmailAddress;
    }

    /**
     * Sets from email address.
     *
     * @param fromEmailAddress the from email address
     */
    public void setFromEmailAddress(String fromEmailAddress) {
        this.fromEmailAddress = fromEmailAddress;
    }
}
